package org.assistant.csp.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.assistant.common.exception.GetFromDBException;
import org.assistant.common.exception.SaveIntoDBException;
import org.assistant.common.jdbc.core.RowMapper;
import org.assistant.common.jdbc.dao.BasicDao;
import org.assistant.csp.data.RelationUser;

public class RelationUserDaoImpl extends BasicDao implements RelationUserDao {
	private class RelationUserRowMapper implements RowMapper<RelationUser> {
		public RelationUser mapRow(ResultSet rs, int index) throws SQLException {
			RelationUser relationUser = new RelationUser();
			relationUser.setId(rs.getString("relation_user_id_"));
			relationUser.setName(rs.getString("relation_user_name_"));
			relationUser.setHomeId(rs.getString("home_id_"));

			return relationUser;
		}
	}

	/**
	 * 根据ID获取关联用户信息
	 * 
	 * @param relationUserId
	 * @return
	 * @throws GetFromDBException
	 */
	public RelationUser getRelationUserById(String relationUserId)
			throws GetFromDBException {
		String sql = "select relation_user_id_,relation_user_name_,home_id_ from common_relation_users where relation_user_id_=?";

		try {
			return getJdbcTemplate().queryForObject(
				sql, new RelationUserRowMapper(), relationUserId);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("查询关联用户时出错啦：" + e.getMessage());
		}
	}

	/**
	 * 根据家庭ID获取该家庭下的关联用户信息
	 * 
	 * @param homeId
	 * @return
	 * @throws GetFromDBException
	 */
	public List<RelationUser> getRelationUserByHome(String homeId)
			throws GetFromDBException {
		String sql = "select relation_user_id_,relation_user_name_,home_id_ from common_relation_users where home_id_=?";

		try {
			return getJdbcTemplate().queryForList(
				sql, new RelationUserRowMapper(), homeId);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new GetFromDBException("查询关联用户时出错啦：" + e.getMessage());
		}
	}

	/**
	 * 保存关联用户信息
	 * 
	 * @param relationUser
	 * @throws SaveIntoDBException
	 */
	public void insertRelationUser(RelationUser relationUser)
			throws SaveIntoDBException {
		StringBuffer sqlBuff = new StringBuffer();
		sqlBuff.append("insert into common_relation_users(");
		sqlBuff.append("relation_user_id_,relation_user_name_,home_id_) ");
		sqlBuff.append("values(?,?,?)");

		try {
			getJdbcTemplate().update(
				sqlBuff.toString(), relationUser.getId(),
				relationUser.getName(), relationUser.getHomeId());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SaveIntoDBException("保存关联用户时出错啦：" + e.getMessage());
		}
	}
}
